import React, {Component} from 'react';
import ss from '../image/qrcode.png';
import during from '../image/during.png';
import finish from '../image/finish.png';
import map from '../image/map.png';
import {wechat, order} from "../value";
import {config} from "../config";
import app from '../AppMethod';

class Navigation extends Component {
    constructor(props) {
        super(props);
        this.state = {
            editVisible: false,
            editConfirmLoading: false,
            position: {lng: 116.403981, lat: 39.91582},
            BMap: window.BMap,
            map: {},
            pointData: []
        };
    };

    render() {
        return (
            <div style={{width: '100%', height: '100%', border: '0px solid gray'}}>
            <div style={{width: '100%', height: '100%', border: '0px solid gray'}} id="container">

            </div>
                <div className="bottomContainer" style={{position: 'fixed', bottom: 0}}>
                    <div className="bottomLogo" onClick={() => this.handleDropMap('/addOrder')}>
                        <div>
                            <img alt="null" src={ss} style={{width: '24px', height: '24px'}}/>
                        </div>
                        <div className="bottomLogoTitle">扫一扫</div>
                    </div>
                    <div className="bottomLogo">
                        <div>
                            <img alt="null" src={map} style={{width: '24px', height: '24px'}}/>
                        </div>
                        <div className="bottomLogoTitle LogoTitleChoose">查看地图</div>
                    </div>
                    <div className="bottomLogo" onClick={() => this.handleDropMap('/deliveryOrder')}>
                        <div>
                            <img alt="null" src={during} style={{width: '24px', height: '24px'}}/>
                        </div>
                        <div className="bottomLogoTitle">配送中</div>
                    </div>
                    <div className="bottomLogo" onClick={() => this.handleDropMap('/finishOrder')}>
                        <div>
                            <img alt="null" src={finish} style={{width: '24px', height: '24px'}}/>
                        </div>
                        <div className="bottomLogoTitle">已配送</div>
                    </div>
                </div>
            </div>
        )
    };

    /**
     * 初始化微信授权以及查询客户的经纬度
     * @returns {Promise.<void>}
     */
    async componentDidMount() {
        this.handleGetOrderList();
        const BMap = this.state.BMap;
        const _this = this;
        var map = new BMap.Map("container");
        let result = await app.post(wechat.GET_SIGNPACKAGE, {url: window.location.href.split("#")[0]});
        if (result.code === 1) {
            let data = result.data;
            window.wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.appId, // 必填，公众号的唯一标识
                timestamp: data.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.nonceStr, // 必填，生成签名的随机串
                signature: data.signature,// 必填，签名
                jsApiList: ['getLocation', 'openLocation'] // 必填，需要使用的JS接口列表
            });
            window.wx.error(function (res) {
                app.alert(JSON.stringify(res), 'error', 3);
            });
        } else {
            app.alert(result.msg, 'error', 4);
        }
        window.wx.getLocation({
            type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
            success: async function (res) {
                let latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                let longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。

                // 微信经纬度转化成百度地图经纬度
                let positionResult = await app.post(wechat.GET_POSITION, {latitude, longitude});

                if (positionResult.code !== 1) {
                    app.alert(result.msg, 'error', 1);
                    return;
                }
                latitude = positionResult.data.y;
                longitude = positionResult.data.x;
                let type = _this.props.match.params.type;
                if (type == 1) {
                    var point = new BMap.Point(longitude, latitude);
                    map.centerAndZoom(point, 11);
                    let latLon = longitude + "," + latitude;
                    let myArr = [];
                    myArr.push(latLon);
                    let mapArr = _this.state.pointData;
                    let markerArr = myArr.concat(mapArr);
                    for (var i = 0; i < markerArr.length; i++) {
                        var p0 = markerArr[i].split(",")[0];
                        var p1 = markerArr[i].split(",")[1];
                        _this.addMarker(new BMap.Point(p0, p1), i, BMap, map);
                    }
                } else if (type == 0) {
                    let destinationx = app.getData('customer_x');//经度
                    let destinationy = app.getData('customer_y');//纬度
                    let customer_name = app.getData('customer_name');
                    if (destinationx && destinationy) {
                        let url = "http://api.map.baidu.com/marker?location=" + destinationy + "," + destinationx + "&title=目的位置&content=" + customer_name + "&output=html";
                        window.location.href = url;
                    }
                }
            }
        });
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        }
    }

    /**
     * 添加标注
     * @param point
     * @param index
     * @param BMap
     * @param map
     */
    addMarker(point, index, BMap, map) {
        let myIcon;
        if (index == 0) {
            myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png",
                new BMap.Size(23, 25), {
                    offset: new BMap.Size(10, 25),
                    imageOffset: new BMap.Size(0, 0 - 10 * 25)
                });
        } else if (index > 10) {
            myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png",
                new BMap.Size(23, 25), {
                    offset: new BMap.Size(10, 25),
                    imageOffset: new BMap.Size(0, 0 - 11 * 25)
                });
        } else {
            myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png",
                new BMap.Size(23, 25), {
                    offset: new BMap.Size(10, 25),
                    imageOffset: new BMap.Size(0, 0 - (index - 1) * 25)
                });
        }
        let marker = new BMap.Marker(point, {icon: myIcon});
        map.addOverlay(marker);
        return marker;
    };

    /**
     * 根据负责人id 查询客户的经纬度，用户地图展示
     * @returns {Promise.<void>}
     */
    async handleGetOrderList() {
        this.setState({loading: true});
        let employee_id = app.getData('employee_id');
        let result = await app.post(order.QUERY_OUTPUTGROUPBYCUSTOMER, {employee_id: employee_id});
        if (result.code === 1) {
            let data = result.data.dataSet;
            let pointData = [];
            for (let i = 0; i < data.length; i++) {
                if (data[i].output_logistics_type == 1) {
                    continue;
                }
                if(data[i].output_logistics_type==2){
                    data[i].customer_x=data[i].logistics_x;
                    data[i].customer_y=data[i].logistics_y;
                }
                let point = data[i].customer_x + ',' + data[i].customer_y;
                pointData.push(point);
            }
            this.setState({pointData});
        } else {
            this.setState({pointData: []});
        }
    };

    /**
     * 处理页面跳转事件
     * @param path
     */
    handleDropMap(path) {
        this.props.history.push(config.path + path);
    };
};

export default Navigation;